package com.jiedeng.controller.index;

import com.jiedeng.dao.*;
import com.jiedeng.entity.PostDetails;
import com.jiedeng.entity.ProjectCount;
import com.jiedeng.entity.ProjectDetails;
import com.jiedeng.mapper.ProjectMapper;
import com.jiedeng.model.*;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 首页
 *
 * @author zhouyb
 */
@RestController
@Scope("prototype")
@RequestMapping("/homepage")
public class HomepageController {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ICorpRepository corpRepository;
    @Autowired
    private IProjectRepository projectRepository;
    @Autowired
    private IProjectCorpRepository projectCorpRepository;
    @Autowired
    private ICorpPostRepository corpPostRepository;
    @Autowired
    private IProjectPersonRepository projectPersonRepository;
    @Autowired
    private IPersonRepository personRepository;

    @Autowired
    private IProTypeRepository proTypeRepository;

    /**
     * 查询首页数据
     *
     * @param epsId
     * @param projectName 项目名
     * @param status      状态
     * @param page
     * @param pageSize
     * @param personId    项目id
     * @return 项目详情集合
     */
    @RequestMapping("findProjectCountList")
    public List<ProjectCount> findProjectCountList(String epsId, String projectName, String status, String page, String pageSize, String personId) {
        if (StringUtils.isEmpty(page) || StringUtils.isEmpty(pageSize)) {
            page = "1";
            pageSize = "10";
        }
        if (StringUtils.isEmpty(epsId)) {
            epsId = "0";
        }
        if (StringUtils.isEmpty(status)) {
            status = "3";
        }
        String corpIds = findAllPerson(Long.valueOf(personId));
        if (epsId != null) {
            List<ProjectCount> list = projectMapper.findProjectCountList(Long.parseLong(epsId), projectName, status, page, pageSize, corpIds);
            return list;
        }
        return null;
    }

    /**
     * 查询首页数据总数
     *
     * @param epsId
     * @param projectName
     * @param status
     * @param personId
     * @return
     */
    @RequestMapping("findProjectCountNum")
    public int findProjectCountNum(String epsId, String projectName, String status, String personId) {
        if (StringUtils.isEmpty(epsId)) {
            epsId = "0";
        }

        if (StringUtils.isEmpty(status)) {
            status = "3";
        }
        String corpIds = findAllPerson(Long.valueOf(personId));
        int count = projectMapper.findAllProjectCount(Long.parseLong(epsId), projectName, status, corpIds);
        return count;
    }

    /**
     * 查询单位信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getCorpById", method = RequestMethod.GET)
    public Corp getCorpById(long id) {
        //List<Corp> corpList=
        return corpRepository.findAllById(id);
    }

    /**
     * 查询照片数据名称
     *
     * @param projectId 项目id
     * @param taskId    任务id
     * @param closeDo   状态
     * @return FileRecord集合
     */

    @RequestMapping("findphotoCountList")
    public List<FileRecord> findphotoCountList(String projectId, String taskId, String closeDo) {
      /*  if (StringUtils.isEmpty(page) || StringUtils.isEmpty(pageSize)) {
            page = "1";
            pageSize = "10";
        }*/
        List<FileRecord> list = new ArrayList<>();
        if (!StringUtils.isEmpty(taskId)) {
            list = projectMapper.findPhotoCountList(Long.parseLong(projectId), taskId, Integer.parseInt(closeDo));
        }
        return list;
    }

    /**
     * 查询照片总数
     *
     * @param projectId
     * @return
     */
    @RequestMapping("findphotoCountNum")
    public int findphotoCountNum(String projectId) {
        if (StringUtils.isEmpty(projectId)) {
            projectId = "0";
        }
        if (projectId != null) {
            int count = projectMapper.findAllphotoCount(Long.parseLong(projectId));
            return count;
        }
        return 0;
    }

    /**
     * 查询任务
     *
     * @param projectId 项目id
     * @param page
     * @param pageSize
     * @return Task集合
     */

    @RequestMapping("findtaskCountList")
    public List<Task> findtaskCountList(String projectId, String page, String pageSize) {
        if (StringUtils.isEmpty(page) || StringUtils.isEmpty(pageSize)) {
            page = "1";
            pageSize = "10";
        }
        List<Task> list = new ArrayList<>();
        if (!StringUtils.isEmpty(projectId)) {
            list = projectMapper.findtaskCountList(Long.parseLong(projectId), page, pageSize);
        }
        return list;
    }

    /**
     * 查询任务总数
     *
     * @param projectId
     * @return
     */
    @RequestMapping("findtaskCountNum")
    public int findAlltaskCount(String projectId) {
        if (StringUtils.isEmpty(projectId)) {
            projectId = "0";
        }
        if (projectId != null) {
            int count = projectMapper.findtaskCountNum(Long.parseLong(projectId));
            return count;
        }
        return 0;
    }

    /**
     * 查询工程详情信息
     *
     * @param projectId 项目id
     * @return 项目详情
     */
    @RequestMapping("findProjectDetails")
    public ProjectDetails findProjectDetails(String projectId) {
        if (!StringUtils.isEmpty(projectId)) {
            ProjectDetails projectDetails = new ProjectDetails();
            Optional<Project> projectOptional = projectRepository.findById(Long.valueOf(projectId));
            if (projectOptional.isPresent()) {
                Project project = projectOptional.get();
                projectDetails.setId(project.getId());
                projectDetails.setCaption(project.getCaption());
                projectDetails.setCap(project.getCap());
                projectDetails.setStime(project.getStime());
                projectDetails.setEtime(project.getEtime());
                projectDetails.setAddtime(project.getAddtime());
                Optional<ProType> proTypeOptional = proTypeRepository.findById((int) project.getProTypeId());
                if (proTypeOptional.isPresent()) {
                    ProType proType = proTypeOptional.get();
                    projectDetails.setProTypeName(proType.getCaption());
                }
                Optional<Person> personOptional = personRepository.findById(project.getCreater());
                if (personOptional.isPresent()) {
                    Person createrPerson = personOptional.get();
                    projectDetails.setCreaterName(createrPerson.getName());
                }
                Optional<Person> checkerPersonOptional = personRepository.findById(project.getChecker());
                if (checkerPersonOptional.isPresent()) {
                    Person checkerPerson = checkerPersonOptional.get();
                    projectDetails.setCheckerName(checkerPerson.getName());
                }
                projectDetails.setCheckTime(project.getCheckTime());
                ///原查单位
              /*  //建设管理单位
                long corpPropId = 2;
                List<ProjectCorp> projectCorps = projectCorpRepository.findByCorpPropIdAndProjectId(corpPropId, project.getId());
                if (projectCorps != null && projectCorps.size() > 0) {
                    Corp corp = corpRepository.getOne(projectCorps.get(0).getCorpId());
                    //projectDetails.setConstructionName(corp.getCaption());
                }
                //监理单位
                corpPropId = 4;
                List<ProjectCorp> projectCorps1 = projectCorpRepository.findByCorpPropIdAndProjectId(corpPropId, project.getId());
                if (projectCorps1 != null && projectCorps1.size() > 0) {
                    Corp checkCorp = corpRepository.getOne(projectCorps1.get(0).getCorpId());
                    //projectDetails.setSupervisorName(checkCorp.getCaption());
                }
                //施工单位
                corpPropId = 5;
                List<ProjectCorp> projectCorps2 = projectCorpRepository.findByCorpPropIdAndProjectId(corpPropId, project.getId());
                if (projectCorps2 != null && projectCorps2.size() > 0) {
                    Corp exeCorp = corpRepository.getOne(projectCorps2.get(0).getCorpId());
                    projectDetails.setContractorName(exeCorp.getCaption());
                }*/
                ///原查询岗位人员信息
            /*    //建设管理单位岗位
                List<PostDetails> constructionPostList = getPostDeatilsList(9200, 9300, project.getId());

                projectDetails.setConstructionPostList(constructionPostList);
                //监理单位岗位
                List<PostDetails> supervisorPostList = getPostDeatilsList(9400, 9500, project.getId());
                projectDetails.setSupervisorPostList(supervisorPostList);


                //施工单位岗位
                List<PostDetails> contractorPostList = getPostDeatilsList(9500, 9600, project.getId());
                projectDetails.setContractorPostList(contractorPostList);*/

                return projectDetails;

            }
        }
        return null;
    }

    /**
     * 获取项目-单位对应的 岗位人员
     *
     * @param corpPropId 施工单位 5 建设管理单位 2 监理单位 4
     * @param projectId  项目id
     * @param corpId     单位id
     * @return
     */
    @RequestMapping("findPostDetails")
    public List<PostDetails> findPostDetails(long corpPropId, long projectId, long corpId) {
        int startId = 0;
        int endId = 0;
        if (corpPropId == 2) {
            startId = 9200;
            endId = 9300;
        }
        if (corpPropId == 4) {
            startId = 9400;
            endId = 9500;
        }
        if (corpPropId == 5) {
            startId = 9500;
            endId = 9600;
        }
        return getPostDeatilsList(startId, endId, projectId, corpId);
    }

    /**
     * 查询项目对应单位
     *
     * @param corpPropId 施工单位 5 建设管理单位 2 监理单位 4
     * @param projectId  项目id
     * @return
     */
    @RequestMapping("getCorpList")
    public List<Corp> getCorpList(long corpPropId, long projectId) {
        //
        List<ProjectCorp> projectCorps2 = projectCorpRepository.findByCorpPropIdAndProjectId(corpPropId, projectId);
        List<Corp> corpList = new ArrayList<>(10);
        if (projectCorps2 != null && projectCorps2.size() > 0) {
            for (ProjectCorp projectCorp : projectCorps2) {
                Optional<Corp> exeCorp = corpRepository.findById(projectCorp.getCorpId());
                if (exeCorp.isPresent()) {
                    corpList.add(exeCorp.get());
                }
            }
        }
        return corpList;
    }

    /**
     * 查岗位
     *
     * @param startId
     * @param endId
     * @param projectId
     * @param corpId
     * @return
     */
    public List<PostDetails> getPostDeatilsList(int startId, int endId, long projectId, long corpId) {
        List<PostDetails> postDetailsList = new ArrayList<>();
        List<CorpPost> buildCorpPosts = corpPostRepository.findByIdBetween(startId, endId);
        for (CorpPost corpPost : buildCorpPosts) {
            PostDetails postDetails = new PostDetails();
            postDetails.setPostNam(corpPost.getCaption());
            List<String> nameList = new ArrayList<>();
            List<ProjectPerson> projectPersonList = projectPersonRepository.findByProjectIdAndPostId(projectId, corpPost.getId());
            for (ProjectPerson projectPerson : projectPersonList) {
                Person person = personRepository.getOne(projectPerson.getPersonId());
                if (corpId != person.getCorpId()) {
                    continue;
                }
                nameList.add(person.getName());
            }
            postDetails.setPersonNames(nameList);
            postDetailsList.add(postDetails);
        }
        return postDetailsList;
    }


    /**
     * 获取用户及子级用户
     *
     * @param personId
     * @return
     */
    public String findAllPerson(long personId) {
        Person person = personRepository.getOne(personId);
        //Person corp = corpRepository.getOne(person.getCorpId());
        Map<Long, Person> map = new ConcurrentHashMap();
        map.put(person.getId(), person);
        getChildrenPerson(person.getId(), map);
        String corpIds = "";
        for (Long personId2 : map.keySet()) {
            if (corpIds != "") {
                corpIds += ",";
            }
            corpIds += findAllPersonCorp(personId2);
        }
        return corpIds;
    }

    public void getChildrenPerson(long personId, Map<Long, Person> map) {
        List<Person> personList = personRepository.findByLeader(personId);
        for (Person person : personList) {
            map.put(person.getId(), person);
            getChildrenPerson(person.getId(), map);
        }
    }

    /**
     * 获取用户单位及子级单位
     *
     * @param personId
     * @return
     */
    public String findAllPersonCorp(long personId) {
        Person person = personRepository.getOne(personId);
        Corp corp = corpRepository.getOne(person.getCorpId());
        Map<Long, Corp> map = new ConcurrentHashMap();
        map.put(corp.getId(), corp);
        getChildrenCorp(corp.getId(), map);
        String corpIds = "";
        for (Long corpId : map.keySet()) {
            if (corpIds != "") {
                corpIds += ",";
            }
            corpIds += corpId;
        }
        return corpIds;
    }

    public void getChildrenCorp(long corpId, Map<Long, Corp> map) {
        List<Corp> corpList = corpRepository.findAllByRelationShip(corpId);
        for (Corp corp : corpList) {
            map.put(corp.getId(), corp);
            getChildrenCorp(corp.getId(), map);
        }
    }

    /**
     * 根据corpid过去所有对应下级corp
     *
     * @param corpId
     * @return
     */
    public List<Long> findAllCorpByCorpId(long corpId) {
        Corp corp = corpRepository.getOne(corpId);
        Map<Long, Corp> map = new ConcurrentHashMap();
        map.put(corp.getId(), corp);
        getChildrenCorp(corp.getId(), map);
        List<Long> corpIds = new ArrayList<>(10);
        for (Long corpId2 : map.keySet()) {
            corpIds.add(corpId2);
        }
        return corpIds;
    }

    /**
     * 根据单位获取岗位，包含下级
     *
     * @param corpId 单位id
     * @return CorpPost集合
     */
    @RequestMapping(value = "/getCorpPostByCorpIds", method = RequestMethod.GET)

    public List<CorpPost> getCorpPostProjectByCorpIds(long corpId) {
        List<Long> corpIds = findAllCorpByCorpId(corpId);
        return corpPostRepository.findCorpPostByCorpIdsSQL(corpIds);
    }

    /**
     * 获取项目
     *
     * @param personId
     * @return
     */
    @RequestMapping(value = "/allProject", method = RequestMethod.GET)
    public List<Project> getAllProjectByPersonId(String personId) {
        String corpIds = findAllPerson(Long.valueOf(personId));
        List<Project> projects = projectMapper.findProjectByCorpIds(null, "3", corpIds);
        List<Project> projectList = new ArrayList<>();
        Map<Long, String> checkRepeat = new HashMap<Long, String>();
        for (Project project : projects) {
            if (!checkRepeat.containsKey(project.getId())) {
                checkRepeat.put(project.getId(), "记录是否存在！");
                projectList.add(project);
            }
        }
        return projectList;
    }

    /**
     * 获取项目 -基础报表
     *
     * @param personId 用户id
     * @return 项目集合
     */
    @RequestMapping(value = "/allProjectByPersonIdAndCorpId", method = RequestMethod.GET)
    public List<ProjectDetails> findProjectByCorpIdsAndPersonId(String personId) {
        String corpIds = findAllPerson(Long.valueOf(personId));
        List<ProjectDetails> projects = projectMapper.findProjectByCorpIdsAndPersonId(corpIds, Long.valueOf(personId));
        List<ProjectDetails> projectList = new ArrayList<>();
        Map<Long, String> checkRepeat = new HashMap<Long, String>();
        for (ProjectDetails project : projects) {
            if (!checkRepeat.containsKey(project.getId())) {
                checkRepeat.put(project.getId(), "记录是否存在！");
                projectList.add(project);
            }
        }
        return projectList;
    }
}
